<?php

/*
* 上传案件
*/

class CaseauditController extends Controller_Base
{
    public function init()
    {
        parent::init();

    }
    /**
     * 录入案件审核列表页
     */
    public function indexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $source = intval($request->getQuery('source', 1));
        $limit = intval($request->getQuery('limit', 10));
        $mediationOrganId  = intval($request->getQuery('mediationOrganId', 0));
        $assetsId  = intval($request->getQuery('assetsId', 0));
        $importRecordId = intval($request->getQuery('importRecordId', 0));
        $batshId = $request->getQuery('batshId', '');
        $litigantName = $request->getQuery('litigantName', '');
        $batchName = $request->getQuery('batchName', '');
        $where = $this->getWhere();
        if($mediationOrganId){
            array_push($where,"mediationOrganId = ".$mediationOrganId);
        }
        if($assetsId){
            array_push($where,"assetsId = ".$assetsId);
        }
        if($importRecordId){
            array_push($where,"importRecordId = ".$importRecordId);
        }
        if($batshId){
            array_push($where,"batshId = '{$batshId}'");
        }
        if($batchName){
            array_push($where,"batchName = '{$batchName}'");
        }
        if($litigantName){
            $caseId = $this->getCaseIdByLitigantName($litigantName);
            if($caseId){
                array_push($where,"id in ({$caseId})");
            }
        }
        $add_begin_end = trim($this->getRequest()->getQuery('add_begin_end', ''));
        if ($add_begin_end){
            $date_tmp =  explode(" 到 ",$add_begin_end);

            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "addTime <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "addTime >= {$begin_date}");
            }
        }
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $query = [
            'mediationOrganId' => $mediationOrganId,
            'assetsId' => $assetsId,
            'importRecordId' => $importRecordId,
            'batshId' => $batshId,
            'litigantName' => $litigantName,
            'add_begin_end' => $add_begin_end,
            'batchName' => $batchName,
            'limit' => $limit,
        ];
        array_push($where, "caseSource = {$source} and sysStatus = 1 and caseStatus = 'case_audit'");
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'id DESC'
        );
        $cases = Module_Mediate_Case::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $count = Module_Mediate_Case::getInstance()->getAllBySearch(array("count(*) as num","sum(debtTotal) as debtTotal","sum(debtAmount) as debtAmount",'COUNT(DISTINCT cardId) as groupTotal'), array('where' => $where), true);
        $total = $count[0]['num'];
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        SmartyAdapter::assign('source', $source);
        SmartyAdapter::assign('arrList', $cases);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('debtTotal', empty($count[0]['debtTotal']) ? 0 : $count[0]['debtTotal']);
        SmartyAdapter::assign('debtAmount',  empty($count[0]['debtAmount']) ? 0 : $count[0]['debtAmount']);
        SmartyAdapter::assign('groupTotal', empty($count[0]['groupTotal']) ? 0 : $count[0]['groupTotal']);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('page_query', http_build_query($query));
    }
    /**
     * 审核状态,驳回通过
     */
    public function auditAction()
    {
        $request = $this->getRequest();
        $caseId = ($request->getPost('case_id', []));
        $auditStatus = ($request->getPost('audit_status', ''));
        if (empty($caseId) || empty($auditStatus) || !in_array($auditStatus, ['pass', 'reject'])) {
            AjaxTool::returnJsonData(4001);
        }
        //查询匹配到调解员的案件，跳过分配
        $already_caseId = [];
        $already = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["id in ({$caseId}) and mediatorId>0"]]);
        if($already){
            $already_caseId = array_column($already,'id');
        }

        //查询需要分配的的案件
        $all_caseId = explode(',',$caseId);

        if($already_caseId){
            $allocate_caseId = array_diff($all_caseId,$already_caseId);
        }else{
            $allocate_caseId = $all_caseId;
        }
        //分配
        if($auditStatus == 'pass'){
            $y = date('Y');
            $mediationNum = SmartyAdapter::getTplVars('mediationNum');
            if($allocate_caseId){
                $saveData = [
                    'caseStatus' => 'case_allocate',
                    'updateTime' => time()
                ];
                $res = Module_Mediate_Case::getInstance()->saveByIds($saveData, implode(',',$allocate_caseId));
            }
            if($already_caseId){
                $saveData = [
                    'caseStatus' => 'case_mediate',
                    'updateTime' => time()
                ];
                $res = Module_Mediate_Case::getInstance()->saveByIds($saveData, implode(',',$already_caseId));
            }
            if($this->admin['mediationOrganId'] != 4){
                @Module_Mediate_Case::getInstance()->saveByIds(['mediationNum' => "CONCAT('粤（{$y}）云商调',id,'号（有）')"], $caseId,["mediationNum=''"]);
            }else{
                @Module_Mediate_Case::getInstance()->saveByIds(['mediationNum' => "CONCAT('（{$y}）{$mediationNum}',id,'号（有）')"], $caseId,["mediationNum=''"]);
            }

        }else{
            $saveData = [
                'sysStatus' => 3,
                'updateTime' => time()
            ];
            $res = Module_Mediate_Case::getInstance()->saveByIds($saveData, $caseId);
        }
        //分配成功，添加日志记录
        if($res){
            $id_arr = explode(',', $caseId);
            foreach ($id_arr as $id){
                $data = [
                    'caseId' => $id,
                    'status' => 'case_audit',
                    'operationUid' => $this->admin['id'],
                    'operationName' => $this->admin['name'],
                    'operationContent' =>"案件审核",
                    'remark' => $auditStatus == 'pass' ? "案件审核通过" : "案件审核驳回",
                    'createTime' => time(),
                ];
                $post_data = [
                    'type' => 'Module_Task_Case',
                    'method' => 'addOperateLog',
                    'data' => $data
                ];
                @Module_Queue_Base::addQueue($post_data);
            }

        }
        AjaxTool::returnJsonData(200, [], '审核成功' );


    }
}
